package com.serviceImpl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.dao.manager.UserMapper;
import com.pojo.User;
import com.service.UserService;
import com.utils.Base64Util;
import com.utils.Base64Utils;
import com.utils.Constant;
import com.utils.Md5Utils;
import com.utils.UUIDUtils;

@Service
public class UserServiceImp implements UserService {

	@Resource
	private UserMapper userMapper;

	@Override
	public User findByUsername(String username) {
		try {
			return userMapper.queryUserFromUsername(username);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public int addUserInfo(Map<String, String> paramsMap) {
		try {
			int count=userMapper.ishasname(paramsMap);
			if(count > 0) {
				return -2;
			}
			User entity = new User();
			entity.setUuid(UUIDUtils.getUUID());
			entity.setUsername(paramsMap.get("username"));
			entity.setPassword(Base64Util.encodeData(paramsMap.get("password")));
			entity.setCreatetime(new Date());
			return userMapper.insertSelective(entity);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return -1;
		}
	}

	@Override
	public List<Map<String, String>> getUserInfo(Map<String, String> paramsMap) {
		String page = paramsMap.get("page");
		if (page == null || "".equals(page)) {
			page = "1";
		}
		String num = paramsMap.get("num");
		if (num == null || "".equals(num)) {
			num = "7";
			paramsMap.put("num", num);
		}
		int start = (Integer.parseInt(page) - 1) * Integer.parseInt(num);
		paramsMap.put("start", start + "");
		// 如果是后台管理员,就处理
		if (paramsMap.get("username") != null && Constant.ADMIN.contains(paramsMap.get("username"))) {
			paramsMap.put("isadmin", "1");
		}
		return userMapper.getUserInfo(paramsMap);
	}

	@Override
	public int deleteUserInfo(Map<String, String> paramsMap) {
		try {
			return userMapper.deleteUserInfo(paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
			return -2;
		}

	}

	@Override
	public int updateUserInfo(Map<String, String> paramsMap) {
		try {
			User entity = new User();
			entity.setUuid(paramsMap.get("uuid"));
			entity.setUsername(paramsMap.get("username"));
			entity.setPassword(Base64Util.encodeData(paramsMap.get("password")));
			return userMapper.updateUserInfo(entity);
		} catch (Exception e) {
			e.printStackTrace();
			return -2;
		}
	}
	public static void main(String[] args) {
		String a = Md5Utils.MD5Encode("admin", "utf-8",  false);
		System.out.println(a);
		String a1 = Base64Util.encodeData("admin");
		System.out.println(a1);
	}
}